﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Mofang.Utils.LogProvider
{
    public class OperationReader
    {
        private static volatile OperationReader _instance;

        private static volatile IDictionary<string, Dictionary<int, string>> _dicts = new Dictionary<string, Dictionary<int, string>>();

        private static readonly object _locker = new object();

        private OperationReader()
        {
            //_types = InitTypes();
        }

        public static OperationReader Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (_locker)
                    {
                        if (_instance == null)
                        {
                            _instance = new OperationReader();

                        }
                    }
                }
                return _instance;
            }
        }

        #region private methods

        /// <summary>
        /// 读取操作类型
        /// </summary>
        /// <param name="code">enum value</param>
        /// <param name="typeName">enum type name</param>
        /// <returns></returns>
        public string ReadOperate(int code, string typeName)
        {
            var operate = string.Empty;

            Dictionary<int, string> codes = new Dictionary<int, string>();

            if (_dicts.ContainsKey(typeName))
            {
                codes = _dicts[typeName];

                if (codes == null || !codes.ContainsKey(code))
                {
                    codes = LoadCodes(typeName);
                }

            }
            else {
                codes = LoadCodes(typeName);
            }

            //不存在该CODE的名称
            if (codes == null || !codes.ContainsKey(code))
            {
                return string.Empty;
            }

            return codes[code];

        }

        public Dictionary<int, string> LoadCodes(string typeName)
        {
            var rep = new DictCodeRepository();

            var codes = rep.BatchGet(" Parent=@Parent AND IsValid = true ", new { Parent = typeName })
                .ToDictionary(p => int.Parse(p.Code), v => v.Name);

            if (_dicts.ContainsKey(typeName))
            {
                _dicts.Remove(typeName);
            }

            _dicts.Add(typeName, codes);

            return codes;
        }

        #endregion
    }
}
